#' @title Download and configure GDAL binary utilities under windows.
#' @description  This function help to download and install GDAL binary utilities.
#' @param install_path character. path for unzip of GDAL binary utilities
#' @param proxy_url character indicating proxy url. The format is 'http://server_host:port'
#' @param manual logical indicating whether to download gdal binanry tools manually.It only works for windows.The default value is false.If it is true ,the download page will be opened in browser.
#' @param url character indicating the remote repository which contains gdal binary tools to clone.If you are not sure about this parameter,do not change its value.
#' @param ostype character, indicating the type of architecture of os. Currently, the stable arch is win32.
#' @param install_vc_lib logical indicating whether to also install microsoft visual c++ libraries for command line.
#' @return returns an logical value which represents whether GDAL binary installing is successful
#' @import git2r
#' @export
#' @details This function will download gdal binary(with proxy), and set the search path for gdal_setInstallation automatically.
#' @details If manual if true, you have to download files by your hands.Functions will wait until your hit enter to continue and try to complete the rest configuration.
#' @examples
#' install.gdal(install_path='/c/gdalwin')
install.gdal<-function(install_path='c:/gdalwin',proxy_url=NULL,manual=F,
                       url="https://git.oschina.net/seifer_08ms/osgeo4w-bin.git",ostype=NULL,
                       install_vc_lib=T,install_KB2999226=T){
    install_packages()
    if (.Platform$OS.type!='unix'){
        if(is.null(ostype)) {
            if(R.Version()$arch!='x86_64'){
                ostype<-'win32'
                url.baidupan<-'https://pan.baidu.com/s/1nvTkrLv'
            }else{
                ostype<-'win64'
                url.baidupan<-'https://pan.baidu.com/s/1i4ImQYL'
            }
        }
        cat ('using ostype:',ostype,'\n')
        # try to set the path of exsiting folder
        gdal_path<-file.path(install_path,
                             # paste('gisinter_gdal',ostype,sep='-'),
                             # paste('gisinter',ostype,sep='_'),
                             'bin')
        if(!dir.exists(install_path)){
            if(manual){
                cat('Please download and extract zip files into ',
                    install_path,
                    'from your browser ...\n')
                cat('Please pay attention to keep folder structure as ',gdal_path,'\n')
                dir.create(install_path)
                cat ("Press [enter] to continue ",
                     "to open download page ...",'\n')
                line <- readline()
                browseURL(url.baidupan)
                cat ("Press [enter] to continue ",
                     "if you have already finished the previous step ...",'\n')
                line <- readline()
            }else{
                #automatically download gdal binary tools
                if(!dir.exists(install_path)){
                    if(install_vc_lib){
                        temp.path.vc.lib<-file.path(tempdir(),'vc_lib' )
                        if(!dir.exists(temp.path.vc.lib)){
                            git2r::clone(
                                url ='https://git.oschina.net/seifer_08ms/MSVBCRT_AIO_2017.03.11_X86_X64.git',
                                local_path =temp.path.vc.lib,branch = ostype)
                            if(install_KB2999226){
                                # temp.path.KB2999226<-file.path(tempdir(),'KB2999226.msu' )
                                # if(!dir.exists(temp.path.KB2999226)){
                                    cat('installing update for Microsoft(KB2999226)...','\n')
                                    # url_update<-paste0('http://cc.or.download.microsoft.com/download/',
                                        # ifelse(ostype=='win32',
                                               # '4/F/E/4FE73868-5EDD-4B47-8B33-CE1BB7B2B16A/Windows6.1-KB2999226-x86.msu',
                                               # 'F/1/3/F13BEC9A-8FC6-4489-9D6A-F84BDC9496FE/Windows6.1-KB2999226-x64.msu'))
                                    # download.file(url_update,temp.path.KB2999226,mode='wb')
                                    # system(paste('wusa',temp.path.KB2999226,' /quiet /norestart') )
                                # }
                                # type.kb<-ifelse(ostype=='win32','x86','x64')
                                cmd<-paste('wusa',file.path(temp.path.vc.lib,'installer',
                                                            'Windows6.1-KB2999226.msu') ,
                                           ' /quiet /norestart')
                                cat(cmd,'\n')
                                system(cmd)
                            }

                            cat('installing Microsoft Visual C++ libraries....','\n')
                            system(file.path(temp.path.vc.lib,'installer',
                                             'MSVBCRT_AIO_2017.03.11_X86_X64.exe /VERYSILENT'))
                        }
                    }
                    # need to clone files into install_path
                    #library(git2r)
                    dir.create(install_path)
                    if(!is.null(proxy_url)){
                        Sys.setenv(http_proxy  = proxy_url)
                        #clone under proxy
                        repo <- git2r::clone(url = url,
                                             local_path =install_path,
                                             branch = 'win32')
                        Sys.unsetenv('http_proxy')
                    }else{
                        #clone directly
                        repo <- git2r::clone(url = url,
                                             local_path =install_path,
                                             branch = 'win32')
                    }
                }
            }
        }# end of  if(!dir.exists(install_path)){
        cat('try to set the path for gdal binary:','\n')
        cat(gdal_path,'\n')
        WPATH <- Sys.getenv("PATH")
        WPATH1 <- paste(gdal_path, WPATH, sep=";")
        Sys.setenv(PATH=WPATH1)
        options(gdalUtils_gdalPath=NULL)
        gdalUtils::gdal_setInstallation(search_path =gdal_path,rescan = T)

    }else{
        # if os is unix or linux, we should directly set installation of gdal binary Utils
        gdalUtils::gdal_setInstallation()
    }# end of ostype if block
    # return logical value indicating system
    return(!is.null(getOption("gdalUtils_gdalPath")))
}
str_eval=function(x) {return(eval(parse(text=x)))}
install_packages<-function(){

  pkg.names<-c('dplyr',
    'rgdal',
    'maptools',
    'stringr',
    'gdalUtils',
     'ncdf4',
    'raster',
    'data.table',
    'git2r')
    for(i in 1:length(pkg.names)){
        if(!str_eval(paste0('require(',pkg.names[i],')' )))
        {
            install.packages(pkg.names[i])
        }
    }
}
